import { getPatientBaseObject } from '../../../utils/api/patientBase';
import { 
  getNewlyHeartRateData, 
  getWeeklyHeartRateData, 
  getMonthlyHeartRateData,
  getHeartRatePage,
  getTodayConsecutiveAbnormalities
} from '../../../utils/api/heartRate';
import {
  getDailyAnomalyStats,
  getWeeklyAnomalyStats,
  getMonthlyAnomalyStats
} from '../../../utils/api/pressure';

Page({
  data: {
    userInfo: {
      avatarUrl: '',
      displayName: '用户',
      patientName: '',
      patientUid: ''
    },
    isLoading: false,
    hrHighText: '170-200',
    hrLowText: '170-200',
    chartTimeType: 'week',
    chartDateRange: '--',
    currentDate: new Date(),
    selectedDate: '', // YYYY-MM-DD
    showCalendar: false,
    calendarType: 'single', // 'single' | 'range'
    calendarMinDate: null, // 日历最小日期（三个月前）
    calendarMaxDate: null, // 日历最大日期（今天）
    weekStartDate: null,
    weekEndDate: null,
    currentMonth: new Date(), // 当前选择的月份
    chartData: {
      categories: [],
      series: [
        { name: '心率', data: [], color: '#FF6A6A' }
      ]
    },
    sectionTitle: '本周心率基本情况',
    pressureSectionTitle: '今日血压基本情况',
    pressureRiskData: {
      mild: { count: 0, percent: 0 },
      highNormal: { count: 0, percent: 0 }
    }
  },

  async onLoad() {
    try {
      await this.getUserInfo();
      const today = new Date();
      const { start, end } = this.getWeekRange(today);
      
      // 计算日历日期范围（最近三个月）
      const maxDate = new Date();
      const minDate = new Date();
      minDate.setMonth(minDate.getMonth() - 3);
      
      this.setData({
        selectedDate: this.formatDateYMD(today),
        currentDate: today,
        currentMonth: today,
        weekStartDate: start,
        weekEndDate: end,
        chartDateRange: this.formatDateRangeDisplay(start, end),
        calendarMinDate: minDate.getTime(),
        calendarMaxDate: maxDate.getTime()
      });
      // 加载数据
      this.loadData();
    } catch (error) {
      console.error('页面加载失败:', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  onPullDownRefresh() {
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 600);
  },

  // 获取用户信息
  async getUserInfo() {
    const openid = wx.getStorageSync("openid");
    const cachedPatientUid = wx.getStorageSync("patientUid");
    const phoneNumber = wx.getStorageSync("phoneNumber");
    
    let data = {};
    if (cachedPatientUid) {
      data = { patientUid: cachedPatientUid };
    } else if (phoneNumber) {
      data = { phoneNumber: phoneNumber };
    } else if (openid) {
      data = { wxUid: openid };
    } else {
      console.log('未找到登录信息，使用默认头像');
      return;
    }
    
    try {
      const res = await getPatientBaseObject(data);
      if (res && res.code === 0 && res.data && res.data.length > 0) {
        const user = res.data[0];
        const patientName = user.patientName || user.phoneNumber || '用户';
        const displayName = patientName.length > 1 
          ? patientName.charAt(0) + '*' 
          : patientName;
        
        this.setData({
          userInfo: {
            avatarUrl: user.avatarUrl || '/asserts/images/avatar_placeholder.jpg',
            displayName: displayName,
            patientName: patientName,
            patientUid: user.patientUid
          }
        });
        if (user.patientUid) {
          wx.setStorageSync('patientUid', user.patientUid);
        }
      }
    } catch (err) {
      console.error('获取用户信息失败:', err);
    }
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ isLoading: true });
      await this.loadStatistics();
      await this.loadChartData();
      await this.loadPressureData(); // 加载血压数据
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },
  
  // 加载统计数据（心率范围、平均心率、异常次数）
  async loadStatistics() {
    const patientUid = this.data.userInfo && this.data.userInfo.patientUid;
    if (!patientUid) {
      console.warn('patientUid缺失，跳过统计数据加载');
      return;
    }
    
    try {
      const { chartTimeType, selectedDate, weekStartDate, weekEndDate, currentMonth } = this.data;
      
      // 根据当前时间类型获取数据
      let records = [];
      
      if (chartTimeType === 'day') {
        // 获取当天的数据
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        const allRecords = res.records || res.data?.records || res || [];
        console.log(`日视图 ${selectedDate} 的API响应:`, allRecords.length);
        
        // 筛选当天的数据
        records = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = item.uploadTime.split('T')[0];
            return date === selectedDate;
          }
          return false;
        });
        console.log(`日视图 ${selectedDate} 筛选后记录数:`, records.length);
      } else if (chartTimeType === 'week') {
        // 获取一周的数据
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        const allRecords = res.records || res.data?.records || [];
        
        // 筛选出本周的数据
        const weekStart = weekStartDate || this.getWeekRange(new Date()).start;
        const startTime = this.formatDateYMD(weekStart);
        const endDate = new Date(weekStart);
        endDate.setDate(endDate.getDate() + 6);
        const endTime = this.formatDateYMD(endDate);
        
        records = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = item.uploadTime.split('T')[0];
            return date >= startTime && date <= endTime;
          }
          return false;
        });
      } else if (chartTimeType === 'month') {
        // 获取一个月的数据
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        const allRecords = res.records || res.data?.records || [];
        
        // 筛选出当前月份的数据
        const targetMonth = currentMonth || new Date();
        const targetYear = targetMonth.getFullYear();
        const targetMonthNum = targetMonth.getMonth();
        
        records = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = new Date(item.uploadTime);
            return date.getFullYear() === targetYear && date.getMonth() === targetMonthNum;
          }
          return false;
        });
      }
      
      console.log(`${chartTimeType}统计数据，筛选后记录数:`, records.length);
      
      // 计算统计数据
      if (Array.isArray(records) && records.length > 0) {
        const hrValues = records
          .map(item => item && item.heartRate)
          .filter(val => val !== undefined && val !== null && typeof val === 'number');
        
        if (hrValues.length > 0) {
          // 筛选心率过高（>100）和过低（<60）的数据
          const highHrValues = hrValues.filter(val => val > 100);
          const lowHrValues = hrValues.filter(val => val < 60);
          
          let hrHighText = '--';
          let hrLowText = '--';
          
          // 计算心率过高的范围
          if (highHrValues.length > 0) {
            const maxHigh = Math.max(...highHrValues);
            const minHigh = Math.min(...highHrValues);
            hrHighText = `${minHigh}-${maxHigh}`;
          }
          
          // 计算心率过低的范围
          if (lowHrValues.length > 0) {
            const maxLow = Math.max(...lowHrValues);
            const minLow = Math.min(...lowHrValues);
            hrLowText = `${minLow}-${maxLow}`;
          }
          
          this.setData({
            hrHighText: hrHighText,
            hrLowText: hrLowText
          });
          
          console.log('统计数据已更新:', { 
            时间类型: chartTimeType,
            心率过高: hrHighText, 
            心率过低: hrLowText,
            数据条数: hrValues.length
          });
        } else {
          // 有记录但没有有效的心率值
          this.setData({
            hrHighText: '--',
            hrLowText: '--'
          });
          console.log('当前时间范围内无有效心率数据');
        }
      } else {
        // 没有数据时显示默认值
        this.setData({
          hrHighText: '--',
          hrLowText: '--'
        });
        console.log(`${chartTimeType}视图 - 当前时间范围内无数据`);
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
      // 出错时也显示默认值，避免页面显示异常
      this.setData({
        hrHighText: '--',
        hrLowText: '--'
      });
    }
  },

  onBack() { wx.navigateBack({ delta: 1 }); },
  onTimeTypeChange(e) {
    const type = e.currentTarget.dataset.type;
    let sectionTitle = '本周心率基本情况'; // 默认标题
    
    if (type === 'day') {
      sectionTitle = '今日心率基本情况';
    } else if (type === 'week') {
      sectionTitle = '本周心率基本情况';
    } else if (type === 'month') {
      sectionTitle = '本月心率基本情况';
    }
    
    this.setData({ chartTimeType: type, sectionTitle: sectionTitle }, () => {
      if (type === 'day') {
        // 切换到“日”时，将显示为具体日期
        const display = this.formatDateDisplay(this.data.currentDate);
        const ymd = this.formatDateYMD(this.data.currentDate);
        this.setData({ chartDateRange: display, selectedDate: ymd });
      } else if (type === 'week') {
        const { start, end } = this.getWeekRange(this.data.currentDate);
        this.setData({
          weekStartDate: start,
          weekEndDate: end,
          chartDateRange: this.formatDateRangeDisplay(start, end)
        });
      } else if (type === 'month') {
        // 切换到月视图时，显示当前月份
        const monthDisplay = this.formatMonthDisplay(this.data.currentMonth);
        this.setData({
          chartDateRange: monthDisplay
        });
      }
      this.updateChartData();
    });
  },
  onTimeChange(e) {
    const type = e.detail.type;
    this.setData({ chartTimeType: type });
    // 根据时间类型更新数据
    this.updateChartData();
  },
  // 加载图表数据
  async loadChartData() {
    try {
      const { chartTimeType, selectedDate, weekStartDate, weekEndDate, currentMonth } = this.data;
      const patientUid = this.data.userInfo && this.data.userInfo.patientUid;
      if (!patientUid) {
        console.warn('patientUid缺失，跳过图表数据加载');
        return;
      }
      let chartData = { categories: [], series: [{ name: '心率', data: [], color: '#FF6A6A' }] };
      
      if (chartTimeType === 'day') {
        // 获取当天的心率数据
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        console.log('日图表数据响应:', res);
        
        const allRecords = res.records || res.data?.records || res || [];
        // 筛选当天的数据
        const records = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = item.uploadTime.split('T')[0];
            return date === selectedDate;
          }
          return false;
        });
        
        if (Array.isArray(records) && records.length > 0) {
          // 按小时分组
          const hourlyData = new Array(24).fill(null);
          records.forEach(item => {
            const hour = new Date(item.uploadTime).getHours();
            console.log('记录时间:', item.uploadTime, '小时:', hour, '心率:', item.heartRate);
            if (hourlyData[hour] === null || item.uploadTime > hourlyData[hour].uploadTime) {
              hourlyData[hour] = item;
            }
          });
          
          chartData.categories = Array.from({ length: 24 }, (_, i) => `${i}时`);
          chartData.series[0].data = hourlyData.map(item => item ? item.heartRate : null);
          
          // 调试日志：显示所有心率值
          const allHrValues = chartData.series[0].data.filter(v => v !== null);
          console.log('日图表数据已设置，心率值:', allHrValues);
          console.log('完整的24小时数据:', chartData.series[0].data);
          console.log('心率范围:', Math.min(...allHrValues), '-', Math.max(...allHrValues));
        } else {
          console.warn('日图表无数据');
        }
      } else if (chartTimeType === 'week') {
        // 获取一周的心率数据
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        console.log('周图表数据响应:', res);
        
        const allRecords = res.records || res.data?.records || [];
        
        // 计算一周的日期范围
        const weekStart = weekStartDate || this.getWeekRange(new Date()).start;
        const dates = [];
        for (let i = 0; i < 7; i++) {
          const date = new Date(weekStart);
          date.setDate(weekStart.getDate() + i);
          dates.push(this.formatDateYMD(date));
        }
        
        // 按日期分组，取每天最新的数据
        const dailyData = {};
        allRecords.forEach(item => {
          if (item && item.uploadTime && item.heartRate) {
            const date = item.uploadTime.split('T')[0];
            if (dates.includes(date) && (!dailyData[date] || item.uploadTime > dailyData[date].uploadTime)) {
              dailyData[date] = item;
            }
          }
        });
        
        chartData.categories = dates.map(date => {
          const d = new Date(date);
          return `${d.getFullYear()}\n${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        });
        chartData.series[0].data = dates.map(date => dailyData[date] ? dailyData[date].heartRate : null);
        console.log('周图表数据已设置');
      } else if (chartTimeType === 'month') {
        // 获取一个月的心率数据（显示每天的数据点）
        const res = await getHeartRatePage(patientUid, { 
          pageNum: 1, 
          pageSize: 500,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        console.log('月图表数据响应:', res);
        
        const allRecords = res.records || res.data?.records || [];
        console.log('提取的records:', allRecords.length);
        
        if (Array.isArray(allRecords) && allRecords.length > 0) {
          // 获取当前选择的月份
          const targetMonth = currentMonth || new Date();
          const targetYear = targetMonth.getFullYear();
          const targetMonthNum = targetMonth.getMonth();
          console.log('目标月份:', targetYear, '年', targetMonthNum + 1, '月');
          
          // 筛选出当前月份的数据
          const monthRecords = allRecords.filter(item => {
            if (item && item.uploadTime) {
              const date = new Date(item.uploadTime);
              return date.getFullYear() === targetYear && date.getMonth() === targetMonthNum;
            }
            return false;
          });
          
          console.log(`匹配到 ${targetYear}年${targetMonthNum + 1}月 的记录数:`, monthRecords.length);
          
          if (monthRecords.length > 0) {
            // 按日期分组，每天取最新的一条数据
            const dailyData = {};
            monthRecords.forEach(item => {
              if (item && item.uploadTime && item.heartRate) {
                const date = new Date(item.uploadTime).getDate(); // 获取日期（1-31）
                if (!dailyData[date] || item.uploadTime > dailyData[date].uploadTime) {
                  dailyData[date] = item;
                }
              }
            });
            
            // 获取当月的天数
            const daysInMonth = new Date(targetYear, targetMonthNum + 1, 0).getDate();
            
            // 生成完整的日期序列（1-当月天数）
            const dates = Array.from({ length: daysInMonth }, (_, i) => i + 1);
            
            chartData.categories = dates.map(day => 
              `${targetYear}\n${String(targetMonthNum + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
            );
            chartData.series[0].data = dates.map(day => 
              dailyData[day] ? dailyData[day].heartRate : null
            );
            
            console.log('月图表数据已设置, categories:', chartData.categories.length, 'data:', chartData.series[0].data.filter(v => v !== null).length);
          }
        } else {
          console.warn('月图表无数据');
        }
      }
      
      console.log('最终图表数据:', chartData);
      console.log('chartData.series[0].data:', chartData.series[0].data);
      console.log('chartData.categories:', chartData.categories);
      this.setData({ chartData }, () => {
        console.log('图表数据已设置到页面:', this.data.chartData);
      });
      
    } catch (error) {
      console.error('加载图表数据失败:', error);
      wx.showToast({
        title: '加载图表数据失败',
        icon: 'none'
      });
    }
  },

  onOpenCalendar() {
    const { chartTimeType } = this.data;
    console.log('点击日期选择器，当前时间类型:', chartTimeType);
    
    // 更新日历日期范围（最近三个月）
    const maxDate = new Date();
    const minDate = new Date();
    minDate.setMonth(minDate.getMonth() - 3);
    
    // 日/月使用单选，周使用范围选择
    this.setData({
      calendarType: chartTimeType === 'week' ? 'range' : 'single',
      calendarMinDate: minDate.getTime(),
      calendarMaxDate: maxDate.getTime(),
      showCalendar: true
    });
  },

  onCalendarClose() {
    this.setData({ showCalendar: false });
  },
  onCalendarConfirm(e) {
    const { chartTimeType } = this.data;
    if (chartTimeType === 'day') {
      const date = new Date(e.detail);
      this.setData({
        currentDate: date,
        selectedDate: this.formatDateYMD(date),
        chartDateRange: this.formatDateDisplay(date),
        showCalendar: false
      }, () => this.updateChartData());
    } else if (chartTimeType === 'week') {
      const [startTs, endTs] = e.detail;
      const start = new Date(startTs);
      const end = new Date(endTs);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end),
        showCalendar: false
      }, () => this.updateChartData());
    } else if (chartTimeType === 'month') {
      // 月视图：选择的日期用于确定月份
      const date = new Date(e.detail);
      const monthDisplay = this.formatMonthDisplay(date);
      this.setData({
        currentMonth: date,
        chartDateRange: monthDisplay,
        showCalendar: false
      }, () => this.updateChartData());
    } else {
      this.setData({ showCalendar: false });
    }
  },

  onDatePicked(e) {
    // 仅在“日”模式下生效
    const value = e.detail.value; // YYYY-MM-DD
    const date = new Date(value.replace(/-/g, '/'));
    this.setData({
      selectedDate: value,
      currentDate: date,
      chartDateRange: this.formatDateDisplay(date)
    }, () => {
      this.updateChartData();
    });
  },
  onPrevDate() {
    if (this.data.chartTimeType === 'day') {
      const prev = this.shiftDay(this.data.currentDate, -1);
      this.setData({
        currentDate: prev,
        selectedDate: this.formatDateYMD(prev),
        chartDateRange: this.formatDateDisplay(prev)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'week') {
      const start = this.shiftDay(this.data.weekStartDate || this.data.currentDate, -7);
      const end = this.shiftDay(this.data.weekEndDate || this.data.currentDate, -7);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'month') {
      // 月视图：向前一个月（无限制）
      const prevMonth = new Date(this.data.currentMonth);
      prevMonth.setMonth(prevMonth.getMonth() - 1);
      const monthDisplay = this.formatMonthDisplay(prevMonth);
      const yearMonth = `${prevMonth.getFullYear()}年${prevMonth.getMonth() + 1}月`;
      this.setData({
        currentMonth: prevMonth,
        chartDateRange: monthDisplay
      }, () => this.updateChartData());
      console.log('切换到上个月:', yearMonth);
    } else {
      this.updateChartData();
    }
  },
  onNextDate() {
    if (this.data.chartTimeType === 'day') {
      const next = this.shiftDay(this.data.currentDate, 1);
      this.setData({
        currentDate: next,
        selectedDate: this.formatDateYMD(next),
        chartDateRange: this.formatDateDisplay(next)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'week') {
      const start = this.shiftDay(this.data.weekStartDate || this.data.currentDate, 7);
      const end = this.shiftDay(this.data.weekEndDate || this.data.currentDate, 7);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'month') {
      // 月视图：向后一个月（无限制）
      const nextMonth = new Date(this.data.currentMonth);
      nextMonth.setMonth(nextMonth.getMonth() + 1);
      const monthDisplay = this.formatMonthDisplay(nextMonth);
      const yearMonth = `${nextMonth.getFullYear()}年${nextMonth.getMonth() + 1}月`;
      this.setData({
        currentMonth: nextMonth,
        chartDateRange: monthDisplay
      }, () => this.updateChartData());
      console.log('切换到下个月:', yearMonth);
    } else {
      this.updateChartData();
    }
  },
  async updateChartData() {
    // 同时更新统计数据、图表数据和血压数据
    await this.loadStatistics();
    await this.loadChartData();
    await this.loadPressureData();
  },

  // 工具：日期格式化
  formatDateYMD(date) {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  },
  formatDateDisplay(date) {
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${m}月${d}日`;
  },
  formatDateRangeDisplay(start, end) {
    const sm = String(start.getMonth() + 1).padStart(2, '0');
    const sd = String(start.getDate()).padStart(2, '0');
    const em = String(end.getMonth() + 1).padStart(2, '0');
    const ed = String(end.getDate()).padStart(2, '0');
    return `${sm}月${sd}日-${em}月${ed}日`;
  },
  formatMonthDisplay(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const currentYear = new Date().getFullYear();
    
    // 如果是当前年份，只显示月份；否则显示年月
    if (year === currentYear) {
      return `${month}月`;
    } else {
      return `${year}年${month}月`;
    }
  },
  shiftDay(date, delta) {
    const d = new Date(date.getTime());
    d.setDate(d.getDate() + delta);
    return d;
  },
  getWeekRange(date) {
    const d = new Date(date.getTime());
    const weekday = d.getDay(); // 0 Sun..6 Sat
    const mondayOffset = weekday === 0 ? -6 : 1 - weekday;
    const start = this.shiftDay(d, mondayOffset);
    const end = this.shiftDay(start, 6);
    return { start, end };
  },

  // 加载血压数据
  async loadPressureData() {
    console.log('🩺 开始加载血压数据...');
    const patientUid = this.data.userInfo && this.data.userInfo.patientUid;
    console.log('patientUid:', patientUid);
    
    if (!patientUid) {
      console.warn('patientUid缺失，跳过血压数据加载');
      return;
    }

    try {
      const { chartTimeType, selectedDate, weekStartDate, weekEndDate, currentMonth } = this.data;
      console.log('当前时间类型:', chartTimeType);
      let res;
      let pressureSectionTitle = '';

      if (chartTimeType === 'day') {
        // 查询一天的血压异常统计
        console.log('调用日血压统计API，参数:', { date: selectedDate });
        res = await getDailyAnomalyStats(patientUid, { date: selectedDate });
        pressureSectionTitle = '今日血压基本情况';
      } else if (chartTimeType === 'week') {
        // 查询一周的血压异常统计 - 传入周一的日期
        const startDate = weekStartDate || this.getWeekRange(new Date()).start;
        const dateParam = this.formatDateYMD(startDate);
        console.log('调用周血压统计API，参数:', { date: dateParam });
        res = await getWeeklyAnomalyStats(patientUid, { date: dateParam });
        pressureSectionTitle = '本周血压基本情况';
      } else if (chartTimeType === 'month') {
        // 查询一个月的血压异常统计
        const targetMonth = currentMonth || new Date();
        const year = targetMonth.getFullYear();
        const month = String(targetMonth.getMonth() + 1).padStart(2, '0');
        const monthParam = `${year}-${month}`; // 格式: YYYY-MM
        console.log('调用月血压统计API，参数:', { month: monthParam });
        res = await getMonthlyAnomalyStats(patientUid, { month: monthParam });
        pressureSectionTitle = '本月血压基本情况';
      }

      console.log('血压异常统计响应:', res);

      // 处理响应数据 - 注意嵌套结构
      const responseData = res.data || res;
      const data = responseData.data || responseData;
      console.log('提取的data:', data);
      console.log('data是数组吗?', Array.isArray(data));
      
      let mildCount = 0;
      let elevatedCount = 0;
      
      if (Array.isArray(data)) {
        console.log('数组第一条数据:', data[0]);
        console.log('数组第一条数据字段:', Object.keys(data[0] || {}));
        
        // 统计轻度和正常高值的数量
        data.forEach(record => {
          const risk = record.RiskAssessment;
          if (risk === '轻度' || risk === '轻度高血压') {
            mildCount++;
          } else if (risk === '正常高值') {
            elevatedCount++;
          }
        });
        
        console.log('统计结果 - 轻度:', mildCount, '正常高值:', elevatedCount);
      } else {
        // 如果是对象（某些API可能直接返回统计结果）
        mildCount = data.mild || 0;
        elevatedCount = data.elevated || 0;
      }
      
      const total = mildCount + elevatedCount;
      const mildPercent = total > 0 ? ((mildCount / total) * 100).toFixed(1) : 0;
      const elevatedPercent = total > 0 ? ((elevatedCount / total) * 100).toFixed(1) : 0;
      
      const pressureRiskData = {
        mild: { 
          count: mildCount, 
          percent: parseFloat(mildPercent)
        },
        highNormal: { 
          count: elevatedCount, 
          percent: parseFloat(elevatedPercent)
        }
      };
      
      console.log('处理后的pressureRiskData:', pressureRiskData);

      this.setData({
        pressureSectionTitle,
        pressureRiskData
      });

      console.log('血压数据已更新:', pressureRiskData);
    } catch (error) {
      console.error('加载血压数据失败:', error);
      // 出错时显示默认值
      this.setData({
        pressureRiskData: {
          mild: { count: 0, percent: 0 },
          highNormal: { count: 0, percent: 0 }
        }
      });
    }
  }
});


